package com.example.htmlToPdf.my;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.*;
import java.util.List;
import java.util.Map;

public class VelocityHelper {

    private static VelocityEngine ve = new VelocityEngine();

    private static void initVelocityEngine(String path){
        ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);// 这是模板所在路径
        ve.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        ve.setProperty(Velocity.INPUT_ENCODING, "UTF-8");//指定编码格式，避免生成模板就造成乱码，影响到转pdf后的文件
        ve.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        ve.init();
    }
    /**
     *  得到模板引擎渲染数据后的文件流
     * @param templatePath 模板所在位置
     * @param out 得到输出流
     * @param paramMap 模板数据k-y
     * @param dataList 模板数据集合
     * @return 流
     */
    public static Writer getWriterByTemplate(String templatePath, OutputStream out, Map paramMap, List dataList){

        File file = new File(templatePath);
        String path = file.getParent();

        initVelocityEngine(path);

        Template template = ve.getTemplate(file.getName(), "utf-8");

        VelocityContext ctx = new VelocityContext();
        ctx.put("paramMap", paramMap);
        ctx.put("dataList", dataList);
        Writer bw;
        if(null != out)
            bw = new BufferedWriter(new OutputStreamWriter(out));
        else
            bw = new StringWriter();
        template.merge(ctx, bw);
        return bw;
    }
}